<template>
    <el-dialog v-model="dialogVisible" title="选择用户" size="800px" :close-on-click-modal="false" append-to-body
        width="800" class="editDialog" align-center>

        <div class="innerPane" style="text-align: center">
            <el-transfer v-model="selected" filterable :filter-method="filterMethod" :titles="['用户列表', '已选用户']"
                @change="handleChange" filter-placeholder="请输入用户名" :data="users" />
        </div>

    </el-dialog>
</template>

<script setup lang="js">
import { ref, defineExpose, reactive } from "vue";
import { ElMessage } from "element-plus";

import { reqUserList, reqUserListBy, reqRoleRelUsers } from "@/utils/requests";

const emits = defineEmits(["confirm"]);

let dialogVisible = ref(false);


const initialForm = () => ({
    roleCode: ''
})
let searchForm = reactive(initialForm());


let users = ref([]);

let selected = ref([]);

const openDialog = (rowData) => {
    dialogVisible.value = true;

    users.value = [];
    selected.value = [];

    searchForm.roleCode = rowData.roleCode;

    search();

    requestCheceked();
};

const search = () => {
    reqUserList({ current: 1, size: 200 }).then(res => {
        users.value.push(...res.records.map(item => ({
            key: item.id,
            label: item.userName + "(" + item.account + ")",
            disabled: false
        })));

    })

};

const requestCheceked = () => {
    reqUserListBy({ roleCode: searchForm.roleCode }).then(res => {
        selected.value = res;
    });
};

const filterMethod = (query, item) => {
    return item.label.indexOf(query) > -1;
};

const handleChange = (newTargetKeys, direction, moveKeys) => {

    let isAdd = (direction === "right" ? 1 : 0)

    reqRoleRelUsers({ isAdd: isAdd, roleCode: searchForm.roleCode, userIds: moveKeys.join(",") })
        .then(res => {
            ElMessage.success(isAdd === 1 ? "用户添加关联成功" : "用户取消关联成功");
        }).catch((err) => {
            ElMessage.error(err.message || "请求失败");
        });
};


defineExpose({ openDialog });
</script>

<style scoped>
.transfer-footer {
    margin-left: 15px;
    padding: 6px 5px;
}
</style>
